<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Moff_play extends MY_Model
{
    public function __construct()
    {
        parent::__construct();
    }
    
    public function noteUserOffDb($user_id)
    {
        $count = $this->db->query("SELECT `id` FROM `off_scores` WHERE `user_id` = ".$user_id." AND month = ".date('m')." AND year = ".date('Y') )-> num_rows();
		if( $count == 0 ){
			$datax = array(
				"user_id" => $user_id,
                "month" => date('m'),
                "year" => date('Y'),
				"scores" => 0,
				"time" => 0,
				"created" => date('Y-m-d H:i:s')
			);
			$this->db->insert('off_scores', $datax);
		}

    }
    
    public function get_question_db()
	{
		$this->db->update("off_scores",array( "current_scores" => 0 ),"user_id =".$this->session->userdata('user_id'));
		
		$data_categories = $this->db->query("SELECT * FROM off_questions_categories ")->result_array();
		$arr = Array();
		foreach ( $data_categories as $item ){
			$data = $this->db->query("SELECT id,content FROM off_questions WHERE categories_id = ".$item['id']." ORDER BY rand() LIMIT 1 ")->row_array();
			array_push($arr,$data);
		}
		$this->updateTime();
		return json_encode($arr);
	}
	
	
	public function check_answer($id,$choice){
		$data = $this->db->query("SELECT id, answer, categories_id FROM off_questions WHERE id = ".$id )->row_object();
		if( $data->answer == $choice ){
			$this->updateScore($data->categories_id);
			$current_scores = $this->db->query("SELECT current_scores FROM off_scores WHERE user_id = ".$this->session->userdata('user_id')." AND month = ".date('m')." AND year = ".date('Y') )->row_object()->current_scores;
			return json_encode(array( "status"=>200, "current_scores" => $current_scores));
		}else{
			return $data->answer;
		}
	}
	
	private function updateTime(){
		$time = ($this->microtime_float()) + 3000; // milisecond
		$data = array( 
			'time' => $time
			);
		$this->db->update("off_scores",$data,"user_id =".$this->session->userdata('user_id')." AND year = ".date('Y'));
		//$this->db->update('user', $data, 'id ='.$id);
	}
	
	private function deltaTime(){
		$time = $this->microtime_float(); // milisecond
		$datax = $this->db->query("SELECT time FROM off_scores WHERE user_id = ".$this->session->userdata('user_id')." AND month = ".date('m')." AND year = ".date('Y') )->row_object();
		$timeanswer = $this->db->query("SELECT content FROM off_settings WHERE type = 'time_answer' ")->row_object()->content;
		$time2 =( $time - $datax->time)/1000 ; // 1000 => second
		$bonus_time = $timeanswer - $time2;
		return (int)($bonus_time);
	}
	
	private function updateScore($categories_id){
	$data = $this->db->query("SELECT score_bonus, score_second_bonus FROM off_questions_categories WHERE id = ".$categories_id )->row_object();
		$score_bonus = $data->score_bonus;
		$score_second_bonus = (int)($data->score_second_bonus) * $this->deltaTime();
		$scorex =  $score_bonus +  $score_second_bonus; // điểm từng câu
		$user_id = $this->session->userdata('user_id');
		$datax = $this->db->query("SELECT scores FROM off_scores WHERE user_id = ".$user_id." AND month = ".date('m')." AND year = ".date('Y') )->row_object();
		$score = $datax->scores + $scorex;
		$current_scores = $this->db->query("SELECT current_scores FROM off_scores WHERE user_id = ".$user_id." AND month = ".date('m')." AND year = ".date('Y') )->row_object()->current_scores + $scorex;
		$dataxx = array("scores"=>$score, "current_scores" => $current_scores );
		$this->db->update("off_scores",$dataxx,"user_id =".$this->session->userdata('user_id')." AND month = ".date('m')." AND year = ".date('Y') );
		
		$this->newTimeUpdate();
	}
	
	private function newTimeUpdate(){
		$new_time_update = $this->microtime_float() +3000; // milisecond
		$data = array("time"=>$new_time_update);
		$this->db->update("off_scores",$data,"user_id =".$this->session->userdata('user_id')." AND month = ".date('m')." AND year = ".date('Y') );
	}
    
    public function checkCoin($id)
    {
        $coin = intval($this->db->query('SELECT content FROM setting WHERE type = "pay_offline" AND `active` = 1')->row_object()->content);
        
        $coin_user = $this->db->query('SELECT coin FROM user WHERE id = '.$id)->row_object()->coin;
        $c_user = $coin_user - $coin;
        if($c_user >= 0)
        {
            $codeTrade = 'GAME-'.date('YmdHis').'-'.$this->generateCode(8);
            $content = 'Thanh toán '.$coin.' Xu cho lần chơi Offline ngày '.date('H:i:s d/m/Y').' <br />Mã giao dịch: ' .$codeTrade;
            
            $data = array('codeTrade' => $codeTrade, 'content' => $content, 'id_user' => $id, 'statusTrade' => 1, 'created' => date('Y-m-d H:i:s'));
            
            $this->db->insert('logTrade', $data);
            
            $this->db->update('user', array('coin' => $c_user), 'id ='.$id);
            $data_session = array('paymentPlay' => 1);
            $this->session->set_userdata($data_session);
            return 200;
        }else{
            
            $codeTrade = 'GAME-'.date('YmdHis').'-'.$this->generateCode(8);
            $content = 'Thanh toán thất bại '.$coin.' Xu cho lần chơi Offline ngày '.date('H:i:s d/m/Y').'. <b>Mã thất bại:</b> thiếu tiền trong tài khoản. <br />Mã giao dịch: ' .$codeTrade;
            
            $data = array('codeTrade' => $codeTrade, 'content' => $content, 'id_user' => $id, 'statusTrade' => 0, 'created' => date('Y-m-d H:i:s'));
            
            $this->db->insert('logTrade', $data);
            
            return 500;
        }
        
    }
    
}
